//
//  YXDownloadViewController.m
//  MockProject
//
//  Created by 周丽丽 on 16/8/24.
//  Copyright © 2016年 niuzhaowang. All rights reserved.
//

#import "YXDownloadViewController.h"
#import "YXDownloadTableViewCell.h"
#import "YXDownloadManger.h"
#import "YXDownloader.h"
static NSString *const KAllTaskStart = @"全部开始";
static NSString *const KAllTaskStop = @"全部暂停";
@interface YXDownloadViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *taskStateButton;
@property (nonatomic, strong) UILabel *downloadCountLabel;
@property (nonatomic, strong) UILabel *noTaskLabel;
@property (nonatomic, strong) YXDownloadManger *manger;
@property (nonatomic, strong) NSMutableArray<YXDownloader *> *downloadersArr;
@property (nonatomic, assign) AFNetworkReachabilityStatus networkState;
@end

@implementation YXDownloadViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    [self setupDownloadTaskListTableView];
    [self setupManger];
    self.downloadersArr = self.manger.taskDownloadArr;
    [self setupNotaskLabel];
    [self setupHeaderView];
    [self isConnectionAvailable];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.downloadersArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *downloadTableViewCellID = @"downloadTableViewCellID";
    YXDownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:downloadTableViewCellID];
    if (!cell) {
        cell = [[YXDownloadTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:downloadTableViewCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.downloadButtonBlock = ^(YXDownloadTableViewCell *cell){
        if (cell.downloader.state == TaskStatePause && self.networkState == ReachableViaWWAN) {
            [self showHud:@"无法手动启动，请去‘设置-通用设置’里进行设置"];
        }else{
            [cell.downloader resumeDownload];
        }
    };
    cell.downloader = self.downloadersArr[indexPath.row];
    return cell;
}
#pragma mark - UITableViewDelegate
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return self.headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 48;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (void)setupManger{
    self.manger = [YXDownloadManger sharedInstance];
    __weak typeof(self)weakSelf = self;
    self.manger.downloaderStateChangeBlock = ^(){
        [weakSelf settingTaskStateButton:weakSelf.taskStateButton];
    };
    self.manger.downloaderCompleteBlockForDownloadVC = ^(){
        weakSelf.downloadersArr = weakSelf.manger.taskDownloadArr;
        [weakSelf.downloadTaskListTableView reloadData];
        [weakSelf judgeWhetherHeaderViewISDisplayed];
    };
}
- (void)setupDownloadTaskListTableView{
    UITableView *downloadTaskListTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    downloadTaskListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    downloadTaskListTableView.delegate = self;
    downloadTaskListTableView.dataSource = self;
    [self.view addSubview:downloadTaskListTableView];
    self.downloadTaskListTableView = downloadTaskListTableView;
}
- (void)setupNotaskLabel{
    UILabel *label = [[UILabel alloc]init];
    label.text = @"您目前还没有下载任务哦";
    label.textColor = [UIColor colorWithHexString:@"ff7000"];
    [self.downloadTaskListTableView addSubview:label];
    self.noTaskLabel = label;
    self.noTaskLabel.hidden = YES;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.downloadTaskListTableView).offset(-50);
        make.centerX.equalTo(self.downloadTaskListTableView);
    }];
}
#pragma mark - HeaderViewInSection
- (void)setupHeaderView{
    UIView *headerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 48)];
    headerV.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    [self.view addSubview:headerV];
    self.headerView = headerV;
    [self judgeWhetherHeaderViewISDisplayed];
    [self setupHeaderUI];
    [self layoutHeaderSubviews];
}
- (void)setupHeaderUI{
    UIButton *taskStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    taskStateBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    taskStateBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [taskStateBtn setTitleColor:[UIColor colorWithHexString:@"403e3d"] forState:UIControlStateNormal];
    [taskStateBtn setTitleColor:[UIColor colorWithHexString:@"403e3d"] forState:UIControlStateSelected];
    [self settingTaskStateButton:taskStateBtn];
    [taskStateBtn setImage:[UIImage imageNamed:@"全部暂停按钮"] forState:UIControlStateNormal];
    [taskStateBtn setImage:[UIImage imageNamed:@"全部开始按钮"] forState:UIControlStateSelected];
    [taskStateBtn addTarget:self action:@selector(taskStateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:taskStateBtn];
    self.taskStateButton = taskStateBtn;
    
    UILabel *downloadCountLbl = [[UILabel alloc]init];
    downloadCountLbl.textAlignment = NSTextAlignmentRight;
    downloadCountLbl.font = [UIFont systemFontOfSize:13];
    downloadCountLbl.textColor = [UIColor colorWithHexString:@"a5a2a1"];
    downloadCountLbl.text = [NSString stringWithFormat:@"(正在下载(%zd)",self.downloadersArr.count];
    [self.headerView addSubview:downloadCountLbl];
    self.downloadCountLabel = downloadCountLbl;
}
- (void)layoutHeaderSubviews{
    [self.taskStateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.headerView);
        make.left.equalTo(self.headerView).offset(15);
        make.right.equalTo(self.headerView.mas_centerX);
    }];
    [self.downloadCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.taskStateButton.mas_right);
        make.right.equalTo(self.headerView).offset(-15);
        make.centerY.equalTo(self.taskStateButton);
    }];
}
- (void)judgeWhetherHeaderViewISDisplayed{
    if (self.downloadersArr.count < 1) {
        self.headerView.alpha = 0;
        self.headerView.hidden = YES;
        self.noTaskLabel.hidden = NO;
    }else{
        self.headerView.alpha = 1;
        self.headerView.hidden = NO;
        self.noTaskLabel.hidden = YES;
    }
}
- (void)settingTaskStateButton:(UIButton *)taskStateButton{
    __block int count = 0;
    [self.downloadersArr enumerateObjectsUsingBlock:^(YXDownloader * _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
        if (downloader.state == TaskStatePause || downloader.state == TaskStateFialed) {
            count++;
        }
    }];
    if (count == self.downloadersArr.count) {
        [taskStateButton setTitle:KAllTaskStart forState:UIControlStateNormal];
    }else if(count < self.downloadersArr.count){
        [taskStateButton setTitle:KAllTaskStop forState:UIControlStateNormal];
    }
    self.downloadCountLabel.text = [NSString stringWithFormat:@"(正在下载(%zd)",self.downloadersArr.count];
}
- (void)taskStateBtnClick:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:KAllTaskStart]) {
        [self.downloadersArr enumerateObjectsUsingBlock:^(YXDownloader * _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
            [downloader resumeDownload];
        }];
        [sender setTitle:KAllTaskStop forState:UIControlStateNormal];
    }else if ([sender.titleLabel.text isEqualToString:KAllTaskStop]){
        [self.downloadersArr enumerateObjectsUsingBlock:^(YXDownloader * _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
            if (downloader.state == TaskStateFialed ) {
                
            }else{
                [downloader pauseDownload];
            }
        }];
        [sender setTitle:KAllTaskStart forState:UIControlStateNormal];
    }
}
#pragma mark -Judge Network Status
-(void) isConnectionAvailable{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: {
                [self showHud:@"未知的网络状况"];
                self.networkState = status;
                break;
            }
            case AFNetworkReachabilityStatusNotReachable: {
                [self showHud:@"当前没有网络哦~"];
                if ([self.taskStateButton.titleLabel.text isEqualToString:KAllTaskStart]) {
                }else if([self.taskStateButton.titleLabel.text isEqualToString:KAllTaskStop]){
                    [self taskStateBtnClick:self.taskStateButton];
                    self.networkState = status;
                }
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                [self showHud:@"当前使用的是手机流量，下载暂停"];
                if (self.manger.downloadingNetworkState) {
                    if ([self.taskStateButton.titleLabel.text isEqualToString:KAllTaskStart]) {
                    }else if([self.taskStateButton.titleLabel.text isEqualToString:KAllTaskStop]){
                        [self taskStateBtnClick:self.taskStateButton];
                        self.networkState = status;
                    }
                }
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: {
                if (self.networkState == AFNetworkReachabilityStatusReachableViaWWAN || self.networkState == AFNetworkReachabilityStatusNotReachable) {
                    if ([self.taskStateButton.titleLabel.text isEqualToString:KAllTaskStart] && self.downloadersArr.count > 0) {
                        [self showHud:@"已连接到WiFi网络"];
                        [self taskStateBtnClick:self.taskStateButton];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self showHud:@"开始下载"];
                        });
                        self.networkState = status;
                    }else if([self.taskStateButton.titleLabel.text isEqualToString:KAllTaskStop]){
                    }
                }
                break;
            }
            default: {
                break;
            }
        }
    }];
    [manager startMonitoring];
}
- (void)showHud:(NSString *)text{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = text;
    hud.margin = 10.f;
    hud.yOffset = 150.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:3];
}
@end
